<script setup lang="ts">
import type { ConfModel } from '@/apis/model/conf'
import type { FormInstance } from '@arco-design/web-vue'
import { getConfApi, updateConfApi } from '@/apis/modules/conf'
import { postAlarmEmailApi } from '@/apis/modules/message'
import { Message } from '@arco-design/web-vue'
import { omit } from 'lodash-es'

const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()

const formState = reactive({
  email_status: false,
  email: '',
  email_frequency: 1440,
  telegram_status: 2,
  telegram_token: '',
  telegram: '',
  telegram_frequency: undefined,
})

function validator(value: string, callback: (...args: any[]) => void) {
  const reg: RegExp
    // eslint-disable-next-line regexp/no-unused-capturing-group
    = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\])|(([a-z\-0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+\.)+[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}))$/i

  if (!value?.trim()) {
    callback('请输入邮箱地址')
    return
  }
  const arr = value.split('\n').filter(item => item)
  if (arr.length > 5) {
    callback('最多只能输入5个')
    return
  }
  for (const item of arr) {
    if (!reg.test(item)) {
      callback('邮箱格式不正确')
      return
    }
  }
  callback()
}
const rules: Record<string, FieldRule> = {
  email_status: { required: true, message: '请选择邮箱告警状态' },
  telegram_status: { required: true, message: '请选择Telegram告警状态' },
  email: {
    required: true,
    validator: (value: string, callback: (...args: any[]) => void) =>
      validator(value, callback),
  },
  email_frequency: { required: true, message: '请输入告警频率' },
}

const btnLoading = ref<boolean>(false)

const route = useRoute()
function onSendTestEmail() {
  btnLoading.value = true
  postAlarmEmailApi({ email: formState.email })
    .then(() => {
      Message.success('发送成功')
    })
    .finally(() => {
      btnLoading.value = false
    })
}

function handleSubmitSuccess() {
  btnLoading.value = true
  const data = {
    type: 3,
    alipay: undefined,
    alipay_hong_kong: undefined,
  }

  if (route.params.module === 'alipay') {
    // @ts-ignore
    data.alipay = formState
  } else {
    // @ts-ignore
    data.alipay_hong_kong = formState
  }
  // @ts-ignore
  updateConfApi({
    type: 3,
    alarm_method: {
      ...omit(formState, ['email_status']),
      email_status: formState.email_status ? 1 : 2,
    },
  })
    .then(() => {
      Message.success('保存成功')
    })
    .finally(() => {
      btnLoading.value = false
    })
}

function getConfigInfo() {
  loading.value = true
  getConfApi({ type: 3 })
    .then((res: ConfModel) => {
      Object.assign(formState, {
        ...omit(res.alarm_method, ['email_status', 'email_frequency']),
      })
      formState.email_status = Number(res.alarm_method?.email_status) === 1
      formState.email_frequency
        = Number(res.alarm_method?.email_frequency) < 1
          ? 1440
          : res.alarm_method?.email_frequency
    })
    .finally(() => {
      loading.value = false
    })
}
onMounted(() => {
  getConfigInfo()
})

watch(() => route.params.module, getConfigInfo)
</script>

<template>
  <main-container
    :loading="loading"
    :pagination="false"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      class="mt-6"
      layout="vertical"
      auto-label-width
      @submit-success="handleSubmitSuccess"
    >
      <a-form-item
        asterisk-position="end"
        label="邮箱"
      >
        <div class="w-[400px] flex flex-col">
          <a-checkbox
            v-model="formState.email_status"
            class="pl-0!"
          >
            开启
          </a-checkbox>
          <span class="relative mt-1 text-xs text-color-3">
            开启后可配置邮箱接收消息
          </span>
        </div>
      </a-form-item>
      <template v-if="Number(formState.email_status) === 1">
        <a-form-item
          asterisk-position="end"
          field="email"
          label="邮箱地址"
          hide-asterisk
        >
          <div class="w-[400px] flex flex-col items-start gap-2">
            <a-textarea
              v-model="formState.email"
              :auto-size="{ maxRows: 5, minRows: 5 }"
              placeholder="请输入邮箱地址，一行一个，最多5个"
            />
            <a-button
              :disabled="!formState.email"
              type="outline"
              @click="onSendTestEmail"
            >
              发送测试消息
            </a-button>
          </div>
        </a-form-item>
        <a-form-item
          asterisk-position="end"
          field="email_frequency"
          label="告警频率"
          hide-asterisk
        >
          <div class="flex flex-col">
            <cloud-input-number
              v-model="formState.email_frequency"
              :min="0"
              class="w-400px!"
              :max="43200"
            >
              <template #append>
                分钟 / 次
              </template>
            </cloud-input-number>
            <div class="mt-1 text-xs text-color-3">
              同一对象多次告警间隔在配置时间内，不会重复发送告警
            </div>
          </div>
        </a-form-item>
      </template>

      <a-form-item class="submit-btn-form mb-0!">
        <a-button
          type="primary"
          html-type="submit"
          :loading="btnLoading"
          class="w-18"
        >
          保存
        </a-button>
      </a-form-item>
    </a-form>
  </main-container>
</template>

<style scoped lang="less">
.arco-form {
  :deep(.arco-form-item-label) {
    display: flex;
  }
}
:deep(.arco-textarea) {
  padding: 4px 10px;
  &::placeholder {
    @apply text-xs text-color-3;
  }
  @apply text-xs;
}
.submit-btn-form {
  :deep(.arco-form-item-label-col) {
    @apply mb-0;
  }
}
</style>
